package com.hotel.front;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Util;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.gson.Gson;
import com.hotel.BL.GenericLogic;
import com.hotel.BL.MasterCreator;
import com.hotel.BL.NightAuditLogic;
import com.hotel.BL.POSLogic;
import com.hotel.BL.PopupLogic;

import data.CleaningStatus;
import data.CurrencyMaster;
import data.DateTimeFormatMaster;
import data.General;
import data.LanguageMaster;
import data.POS;
import data.ReservationStatus;
import data.passingData.GeneralData;
import data.passingData.ResultData;

@SuppressWarnings("serial")
public class GenerlicLogicService  extends HttpServlet  {
	//http://localhost:8080/generlicLogicService?func=editTimeZone&timeZone=&GMT=
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try{
			String doClass = req.getParameter("func");
			if(doClass.equals("editTimeZone")){
				EditTimeZone(req,resp);
			}else if(doClass.equals("loadGeneralData")){
				LoadGeneralData(req,resp);
			}else if(doClass.equals("savechange")){
				SaveChange(req,resp);
			}else if(doClass.equals("loadLanguage")){
				LoadLanguage(req,resp);
			}else if(doClass.equals("loadCurrency")){
				LoadCurrency(req,resp);
			}else if(doClass.equals("loadDateFormat")){
				LoadDateFormat(req,resp);
			}else if(doClass.equals("loadCleaningStatus")){
				LoadCleaningStatus(req,resp);
			}else if(doClass.equals("GetAllReservationStatus")){
				GetAllReservationStatus(req,resp);
			}else if(doClass.equals("updatePreferences")){
				UpdatePreferences(req,resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void EditTimeZone(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);	
		long hotelId = (Long) session.getAttribute("hotelId");
		String timeZone = req.getParameter("timeZone");
		double GMT = Double.parseDouble(req.getParameter("GMT"));
		
		
		boolean obj = new GenericLogic(req,resp).EditTimeZone(hotelId, timeZone, GMT);
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void LoadGeneralData(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		General g = new PopupLogic(req,resp).LoadGeneral(hotelId);
		GeneralData gData = new GeneralData();
		gData.setAccountFolioOpeningDate(g.isAccountFolioOpeningDate());
		gData.setAuditUseCalendarDate(g.isAuditUseCalendarDate());
		gData.setCheckInTime(g.getCheckInTime());
		gData.setCheckoutCleaningColor(g.getMarkCheckedOutRoom().getColor());
		gData.setCheckoutCleaningStatusTitle(g.getMarkCheckedOutRoom().getTitle());
		gData.setCheckOutTime(g.getCheckOutTime());
		gData.setCurrencyConversionMargin(g.getCurrencyConversionMargin());
		gData.setCurrencyDecimalPlaces(g.getCurrencyDecimalPlaces());
		gData.setDateFormatString(String.valueOf(g.getDateFormat().getId()));
		gData.setDateTimeFormat(g.getDateFormat().getDateTimeFormat());
		gData.setDefaultCurrencyAbreviation(g.getDefaultCurrency().getAbreviation());
		gData.setDefaultCurrencyString(String.valueOf(g.getDefaultCurrency().getId()));
		gData.setDefaultCurrencySymbol(g.getDefaultCurrency().getSymbol());
		gData.setDefaultCurrencyTitle(g.getDefaultCurrency().getTitle());
		gData.setDefaultLanguageString(String.valueOf(g.getDefaultLanguage().getId()));
		gData.setFinancialYearFrom(g.getFinancialYearFrom());
		gData.setFinancialYearTo(g.getFinancialYearTo());
		gData.setGMT(g.getGMT());
		gData.setIncloudetax(g.isIncloudetax());
		gData.setInvoicesExclusiveTax(g.isInvoicesExclusiveTax());
		gData.setLanguageCode(g.getDefaultLanguage().getLanguageCode());
		gData.setLanguageSubCode(g.getDefaultLanguage().getLanguageSubCode());
		gData.setLanguageTitle(g.getDefaultLanguage().getTitle());
		gData.setMarkCheckedOutRoomString(String.valueOf(g.getMarkCheckedOutRoom().getId()));
		gData.setNightAuditTime(g.getNightAuditTime());
		gData.setOccupiedCleaningStatusTitle(g.getOnNightAuditRollOverMarkOccupied().getTitle());
		gData.setOccupiedCleaningColor(g.getOnNightAuditRollOverMarkOccupied().getColor());
		gData.setOnNightAuditRollOverMarkOccupiedString(String.valueOf(g.getOnNightAuditRollOverMarkOccupied().getId()));
		gData.setOnNightAuditRollOverMarkVacantRoomString(String.valueOf(g.getOnNightAuditRollOverMarkVacantRoom().getId()));
		gData.setTaxBreakUp(g.isTaxBreakUp());
		gData.setTimeFormatShow24Hours(g.isTimeFormatShow24Hours());
		gData.setTimeZone(g.getTimeZone());
		g.getUsingCurrencyString();
		if(g.getUsingCurrencyString() != null){
			gData.setUsingCurrency(g.getUsingCurrency());
		}
		
		gData.setVacantCleaningColor(g.getOnNightAuditRollOverMarkVacantRoom().getColor());
		gData.setVacantCleaningStatusTitle(g.getOnNightAuditRollOverMarkVacantRoom().getTitle());
		gData.setCurrencyconvert(g.isCurrencyconvert());
		gData.setAssumechild(g.getAssumechild());
		gData.setAgentcommission(g.getAgentcommission());
		gData.setCoporatediscount(g.getCoporatediscount());
		gData.setNightAuditTime(g.getNightAuditTime());
		gData.setFeeforcancel(g.getFeeforcancel());
		gData.setEnsuretype(g.getEnsuretype());
		gData.setEnsureamount(g.getEnsureamount());
		gData.setIspercentofbooking(g.isIspercentofbooking());
		gData.setIsasperbookingpolicy(g.isIsasperbookingpolicy());
		gData.setEarlycheckintimeamount(g.getEarlycheckintimeamount());
		gData.setEarlycheckouttimeamount(g.getEarlycheckouttimeamount());
		gData.setLatecheckouttimeamount(g.getLatecheckouttimeamount());
		gData.setEarlycheckintimeunit(g.isEarlycheckintimeunit());
		gData.setEarlycheckouttimeunit(g.isEarlycheckouttimeunit());
		gData.setLatecheckouttimeunit(g.isLatecheckouttimeunit());
		gData.setEarlycheckinchargeamount(g.getEarlycheckinchargeamount());
		gData.setEarlycheckoutchargeamount(g.getEarlycheckoutchargeamount());
		gData.setLatecheckoutchargeamount(g.getLatecheckoutchargeamount());
		gData.setEarlycheckinchargeunit(g.getEarlycheckinchargeunit());
		gData.setEarlycheckoutchargeunit(g.getEarlycheckoutchargeunit());
		gData.setLatecheckoutchargeunit(g.getLatecheckoutchargeunit());
		gData.setNoshow_charge(g.getNoshow_charge());
		gData.setNoshow_timeunit(g.isNoshow_timeunit());
		gData.setNoshow_isExpectedArrival(g.isNoshow_isExpectedArrival());
		
		//TEE EDIT
		 
		 String stringId = "";
		 String stringName = "";
		POS pos =  new POSLogic(req,resp).GetPOS(hotelId, "iFront");
		gData.setPosid(String.valueOf(pos.getId()));
		gData.setStringDefaultId(pos.getDefaultCounterString());
		gData.setStringDefaultName(pos.getDefaultCounter().getTitle());
		for(int i=0;i<pos.getCounter().size();i++){
			stringId += pos.getCounter().get(i).getId() + ",";
			stringName += pos.getCounter().get(i).getTitle() + ",";
		}
		stringId = stringId.substring(0, stringId.length()-1);
		stringName = stringName.substring(0, stringName.length()-1);
		gData.setStringId(stringId);
		gData.setStringName(stringName);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(gData));
	}
	
	private void SaveChange(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException, ParseException
	{	
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm",Locale.ENGLISH);
		SimpleDateFormat financialyearformatter = new SimpleDateFormat("dd/MM",Locale.ENGLISH);
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		boolean includetax = Boolean.parseBoolean(req.getParameter("includetax"));
		boolean taxbreakup = Boolean.parseBoolean(req.getParameter("taxbreakup"));
		boolean foliodate = Boolean.parseBoolean(req.getParameter("foliodate"));
		boolean currencyconvert = Boolean.parseBoolean(req.getParameter("currencyconvert"));
		short decimalplaces = Short.parseShort(req.getParameter("decimalplaces"));
		long childold = Long.parseLong(req.getParameter("childold"));
		double commission = Double.parseDouble(req.getParameter("commission"));
		double discount = Double.parseDouble(req.getParameter("discount"));
		double currencymagin = Double.parseDouble(req.getParameter("currencymagin"));
		String language = req.getParameter("language");
		String currency = req.getParameter("currency");
		String dateformat = req.getParameter("dateformat");
		String timezone = req.getParameter("timezone");
		double GMT = Double.parseDouble(req.getParameter("GMT"));
		String occupied = req.getParameter("occupied");
		String vacant = req.getParameter("vacant");
		String checkedoutroom = req.getParameter("checkedoutroom");
		boolean timeformat = Boolean.parseBoolean(req.getParameter("timeformat"));
		Date checkintime = formatter.parse(req.getParameter("checkintime").split(" ")[0]);
		Date checkouttime = formatter.parse((req.getParameter("checkouttime")).split(" ")[0]);
		Date nightaudittime = formatter.parse((req.getParameter("nightaudittime")).split(" ")[0]);
		Date financialyearfrom = financialyearformatter.parse((req.getParameter("financialyearfrom")));
		Date financialyearto = financialyearformatter.parse((req.getParameter("financialyearto")));
		long earlycheckintimeamount = Long.parseLong(req.getParameter("earlycheckintimeamount"));
		Boolean earlycheckintimeunit = Boolean.parseBoolean(req.getParameter("earlycheckintimeunit"));
		double earlycheckinchargeamount = Double.parseDouble(req.getParameter("earlycheckinchargeamount"));
		long earlycheckinchargeunit = Long.parseLong(req.getParameter("earlycheckinchargeunit"));
		long earlycheckouttimeamount = Long.parseLong(req.getParameter("earlycheckouttimeamount"));
		Boolean earlycheckouttimeunit = Boolean.parseBoolean(req.getParameter("earlycheckouttimeunit"));
		double earlycheckoutchargeamount = Double.parseDouble(req.getParameter("earlycheckoutchargeamount"));
		long earlycheckoutchargeunit = Long.parseLong(req.getParameter("earlycheckoutchargeunit"));
		long latecheckouttimeamount = Long.parseLong(req.getParameter("latecheckouttimeamount"));
		Boolean latecheckouttimeunit = Boolean.parseBoolean(req.getParameter("latecheckouttimeunit"));
		double latecheckoutchargeamount = Double.parseDouble(req.getParameter("latecheckoutchargeamount"));
		long latecheckoutchargeunit = Long.parseLong(req.getParameter("latecheckoutchargeunit"));
		
		double chargeamount = Double.parseDouble(req.getParameter("noshowtime"));
		Boolean noshowtimeunit = Boolean.parseBoolean(req.getParameter("noshowtimeunit"));
		Boolean afterthis = Boolean.parseBoolean(req.getParameter("afterthis"));
		
		String posid = req.getParameter("posid");
		String counterid = req.getParameter("counterid");
		String defaultcounter = req.getParameter("defaultcounter");
		GenericLogic genericLogic = new GenericLogic(req,resp);
		for(long i=0;i<2;i++){
			General general = genericLogic.GetGeneral(hotelId);
			general.setIncloudetax(includetax);
			general.setTaxBreakUp(taxbreakup);
			general.setAccountFolioOpeningDate(foliodate);
			general.setCurrencyconvert(currencyconvert);
			general.setCurrencyDecimalPlaces(decimalplaces);
			general.setAssumechild(childold);
			general.setCoporatediscount(discount);
			general.setAgentcommission(commission);
			general.setCurrencyConversionMargin(currencymagin);
			general.setDefaultLanguageString(language);
			general.setDefaultCurrencyString(currency);
			general.setDateFormatString(dateformat);
			general.setTimeZone(timezone);
			general.setGMT(GMT);
			general.setOnNightAuditRollOverMarkOccupiedString(occupied);
			general.setOnNightAuditRollOverMarkVacantRoomString(vacant);
			general.setMarkCheckedOutRoomString(checkedoutroom);
			general.setTimeFormatShow24Hours(timeformat);
			general.setCheckInTime(checkintime);
			general.setCheckOutTime(checkouttime);
			general.setNightAuditTime(nightaudittime);
			general.setFinancialYearFrom(financialyearfrom);
			general.setFinancialYearTo(financialyearto);
			general.setEarlycheckintimeamount(earlycheckintimeamount);
			general.setEarlycheckintimeunit(earlycheckintimeunit);
			general.setEarlycheckinchargeamount(earlycheckinchargeamount);
			general.setEarlycheckinchargeunit(earlycheckinchargeunit);
			
			general.setEarlycheckouttimeamount(earlycheckouttimeamount);
			general.setEarlycheckouttimeunit(earlycheckouttimeunit);
			general.setEarlycheckoutchargeamount(earlycheckoutchargeamount);
			general.setEarlycheckoutchargeunit(earlycheckoutchargeunit);
			
			general.setLatecheckouttimeamount(latecheckouttimeamount);
			general.setLatecheckouttimeunit(latecheckouttimeunit);
			general.setLatecheckoutchargeamount(latecheckoutchargeamount);
			general.setLatecheckoutchargeunit(latecheckoutchargeunit);

			if(i == 1){
				//set attibute that will be update after night audit
				general.setNoshow_charge(chargeamount);
				general.setNoshow_timeunit(noshowtimeunit);
				general.setNoshow_isExpectedArrival(afterthis);
			}
			
			if(i==0){
				genericLogic.UpdateGenerlic(general);
				//SharedCache.clearHotelCacheStartWith(hotelId,"GenericLogic");
				POS pos = new POSLogic(req,resp).GetPOS(Long.parseLong(posid));
				pos.setCounterString(counterid);
				pos.setDefaultCounterString(defaultcounter);
				new POSLogic(req,resp).UpdatePOS(pos);
				session.setAttribute("LanguageCode", 
						new MasterCreator().GetLanguage(Long.parseLong(language)).getLanguageCode());
				session.setAttribute("LanguageSubcode", 
						new MasterCreator().GetLanguage(Long.parseLong(language)).getLanguageSubCode());
				session.setAttribute("isIncludetax",includetax);
			}else{
				new NightAuditLogic(req,resp).Keeping(hotelId,general,"data.General");
			}
		}

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(true));
	}
	
	private void LoadLanguage(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		List<LanguageMaster> obj = new GenericLogic(req,resp).GetAllLanguage();
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void LoadCurrency(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		List<CurrencyMaster> obj = new GenericLogic(req,resp).GetAllCurrencyMaster();
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void LoadDateFormat(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		List<DateTimeFormatMaster> obj = new GenericLogic(req,resp).GetAllDateTimeFormatMaster();
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void LoadCleaningStatus(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);	
		long hotelId = (Long) session.getAttribute("hotelId");
		List<CleaningStatus> obj = new GenericLogic(req,resp).GetAllCleaningStatus(hotelId);
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void GetAllReservationStatus(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		HttpSession session=req.getSession(true);	
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		List<ReservationStatus> obj = new GenericLogic(req,resp).GetReservationStatusByHotelId(hotelId);
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void UpdatePreferences(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}	
		long userid = (Long) session.getAttribute("userid");
		String oldPass = req.getParameter("oldpass");
		String newPass = req.getParameter("newpass");
		boolean data = new GenericLogic(req,resp).ChangePassword(userid,oldPass,newPass);

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(data));
	}
}
